# target
TARGET=nano

BUILD_DIR=build

# gcc
CROSS_COMPILE=arm-none-eabi-
CC=$(CROSS_COMPILE)gcc
AS=$(CROSS_COMPILE)gcc -x assembler-with-cpp
CP=$(CROSS_COMPILE)objcopy
SZ=$(CROSS_COMPILE)size
LD=$(CROSS_COMPILE)ld
DP=$(CROSS_COMPILE)objdump

# SRC 
SRC_C+=$(wildcard src/*.c)
SRC_C_DRIVER+= $(wildcard Drivers/STM32F1xx_HAL_Driver/Src/*.c)


SRC_C_FreeRTOS+=$(wildcard FreeRTOS-Kernel/*.c)
SRC_C_FreeRTOS+=$(wildcard FreeRTOS-Kernel/portable/GCC/ARM_CM3/*.c)
SRC_C_FreeRTOS+=$(wildcard FreeRTOS-Kernel/portable/Common/*.c)
SRC_C_FreeRTOS+=FreeRTOS-Kernel/portable/MemMang/heap_4.c

SRC_C+=printf/src/printf/printf.c

SRC_C+=$(SRC_C_DRIVER)

SRC_C+=$(SRC_C_FreeRTOS)

SRC_LD=link.ld

OBJC=$(addprefix $(BUILD_DIR)/,  $(SRC_C:.c=.o))
 

INC=\
-Isrc \
-Iinc \
-I. \
-IDrivers/CMSIS/Include \
-IDrivers/STM32F1xx_HAL_Driver/Inc \
-IFreeRTOS-Kernel/include \
-IFreeRTOS-Kernel/portable/GCC/ARM_CM3 \
-Iprintf/src/printf \
-Iprintf/src

DEFS+=-DUSE_HAL_DRIVER
#CFLAGS
CFLAGS= \
-mcpu=cortex-m3 \
-mthumb \
-Wall \
-fdata-sections -ffunction-sections \
 -MMD -MP \
 -g \
-gdwarf-2 \
-O0 \
-g3

CFLAGS+= \
# --specs=nano.specs   

CFLAGS+=$(DEFS)

LIBS=\
#-lc -lm
#如果程序并不实际使用系统函数，但是某些代码引用了系统函数，那么可以引入libnosys，以便通过编译。
#LIBS+=-lnosys

# LD FLAGS
LDFLAGS=-mcpu=cortex-m3 \
-Wl,--gc-sections

LDFLAGS+=-T$(SRC_LD) $(LIBS)

LDFLAGS += -Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref
 

#SET PATH %.c %.S
vpath %.c $(sort $(dir $(SRC_C)))
 

ELF=$(BUILD_DIR)/$(TARGET).elf
BIN=$(BUILD_DIR)/$(TARGET).bin
DIS=$(BUILD_DIR)/$(TARGET).dis 

.PHONY : all clean d c download download2

all: $(BUILD_DIR) $(BIN) $(DIS)

$(BUILD_DIR):
	mkdir $@

# cc .c
$(BUILD_DIR)/%.o:%.c 
	@mkdir -p $(@D)
	@echo .CC $<
	@$(CC) $(CFLAGS) -c $< $(INC) -o $@

#as .S
# $(BUILD_DIR)/%.o:%.S 
# 	@echo .AS $<
# 	@$(AS) $(CFLAGS) -c $< $(INC) -o $@

# elf
$(ELF):$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo link elf $@
	@$(CC) $(OBJC) $(OBJS) $(LDFLAGS)  -o $@
	@$(SZ) $@ 

#cp .bin
$(BIN):$(ELF)
	@echo objcopy bin
	$(CP) -O binary -S $< $@


$(DIS):$(ELF)
	@echo objdump dis
	@$(DP) -D -h -s $< > $@

clean:
	rm -rf $(BUILD_DIR)

d:
	make clean
	make all -j8
	make download

c:$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo .o

download:
#  openocd 下载 -s 指定默认目录 -f 都在此目录下工作可以省略前缀
#  program 编程 
	../../tools/xpack-openocd-0.12.0-6/bin/openocd.exe \
	-s ../../tools/xpack-openocd-0.12.0-6/openocd/scripts \
	-f interface/cmsis-dap.cfg \
	-f target/stm32f1x.cfg \
	-c "program build/nano.elf verify reset" \
	-c "reset run" \
	-c exit

download2:
#  openocd 下载 -s 指定默认目录 -f 都在此目录下工作可以省略前缀
#  program 编程 
	../../tools/openocd-rpxx/openocd.exe \
	-s ../../tools/openocd-rpxx/scripts \
	-f interface/cmsis-dap.cfg \
	-f target/stm32f1x.cfg \
	-c "program build/nano.elf verify reset" \
	-c "reset run" \
	-c exit